//
//  FSLPageCollectionViewLayout.swift
//  FSLText
//
//  Created by 我演示 on 2019/11/6.
//  Copyright © 2019 ALLSall. All rights reserved.
//

import UIKit

class FSLPageCollectionViewLayout: UICollectionViewFlowLayout {
    var cols : Int = 4
    var rows : Int = 2
    
    fileprivate var maxWidth : CGFloat
    
    fileprivate lazy var cellAtrrs : [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
}

extension FSLPageCollectionViewLayout {
    override func prepare() {
        super.prepare()
        
        //0: 计算宽度和高度
        let itemW = collectionView!.bounds.width - sectionInset.left - sectionInset.right - minimumInteritemSpacing * CGFloat(cols - 1) / CGFloat(cols)
        let itemH = (collectionView!.bounds.height - sectionInset.top - sectionInset.bottom - minimumLineSpacing*CGFloat(rows - 1) / CGFloat(rows))
        
        //1: 获取一共有多少组
        let sectionCount = collectionView!.numberOfSections
        var prePageCount : Int = 0
          
        //2:获取每组有多少数据
        for i  in 0..<sectionCount {
  
            let itemCount = collectionView!.numberOfItems(inSection: i)
            var prePage : Int = 0
            
            for j  in  0..<itemCount {
                      
                let indexPath = IndexPath(item: j , section: i)
                //2: 根据indexPAthena创建 UICollectionViewLayout
                let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
                
                // 2.3 计算j在该组中的第几页
                let page = j / 8
                let index = j % 8
                
                //3: 设置attr的frame
                 //2.3
                let itemY = sectionInset.top + (itemH + minimumLineSpacing ) * CGFloat(index / cols)
                let itemX = CGFloat(prePageCount) * collectionView!.bounds.width + sectionInset.left + (itemW + minimumInteritemSpacing ) * CGFloat(index % cols)
                 
                attr.frame = CGRect(x: itemX, y: 0, width: itemW, height: itemH )
                
                //4: attrs保存到数组中
                cellAtrrs.append(attr)
                
            }
            
       
            prePageCount  += (itemCount - 1) / (cols * rows) + 1
            
        }
        maxWidth = CGFloat(prePageCount)  * collectionView!.bounds.width
        
        
    }
    
}
extension FSLPageCollectionViewLayout {
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return cellAtrrs
    }
    
}

extension FSLPageCollectionViewLayout {
    override var collectionViewContentSize: CGSize {
        return CGSize.init(width: 0, height: 0)
    }
}
